<script>
// import LabelText from '../comm/LabelText'
import dataApi from '@/view/v/data-api'
import AddFile from '../comm/AddFile.vue'
import fileSelect from '../comm/file-select'
import ajaxApi from '../ajax-api'
import LabelText from '../comm/LabelText'
export default {
  render () {
    let initItem = this.item
    return (
      <dl>
        <dt>文档附件上传</dt>
        <dd class="m1">
          <div class="set-item">
            <div class="tit">一旦使用附件，其他控件将失效</div>
            <div class="it">
              <AddFile ref="vAddImg" onAdd={this.onAdd} onChange={this.onChange} initFiles={initItem ? [initItem] : undefined} btnText="选择附件" hasBtnText="重新选择" isUploading={this.isUploading} onCancel={this.onAbort}/>
            </div>
          </div>
          <div class="set-item">
            <LabelText
              type="number" min="0"
              value={this.speed}
              onInputValue={v => { this.speed = v }}>滚动时间
            </LabelText><span class={this.$style.s}>秒</span>
            <div class="it"></div>
          </div>
        </dd>
      </dl>
    )
  },
  data () {
    return {
      isUploading: false
    }
  },
  computed: {
    speed: {
      get () {
        return dataApi.core.docsAttachment.speed
      },
      set (speed) {
        dataApi.core.docsAttachment.speed = speed
      }
    },
    item () {
      if (this.hasDocsAttachment) {
        return dataApi.core.docsAttachment.list[0]
      }
      return ''
    },
    hasDocsAttachment () {
      return dataApi.core.docsAttachment.list.length > 0
    }
  },
  methods: {
    onAdd () {
      this.upload().finally(() => {
        this.isUploading = false
      })
    },
    async upload () {
      const file = await fileSelect({
        // doc docx 当前系统必须装了word 才支持
        // accept: 'application/pdf,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        fileSizeLimit: 30,
        onError: (error) => {
          this.$toast.error(error.message)
        }
      })
      if (!/\.(pdf|docx?|pptx?|xlsx?)$/.test(file.name)) {
        this.$toast.error('只能上传 pdf doc docx ppt pptx xls xlsx 格式文件')
        return
      }
      this.isUploading = true
      const { vAddImg } = this.$refs
      const { url } = await ajaxApi.uploadOfficeTransitionPdf({
        file,
        onProgress: (p) => {
          vAddImg.progressText = ~~(p * 100 - 1) + '%'
        },
        cancelToken: cancel => {
          this.abortFileUpload = cancel
        }
      })
      vAddImg.progressText = ''
      vAddImg.addSingle({
        name: file.name,
        url
      })
    },
    onChange ({ 0: image }) {
      dataApi.core.docsAttachment.list = image ? [image] : []
    },
    onAbort () {
      this.abortFileUpload()
    }
  }
}
</script>
<style module>
.s {
  color: #666;
}
</style>
